package com.geyue.core.service.impl;

import com.geyue.common.base.service.impl.BaseServiceImpl;
import com.geyue.common.toolbox.result.Res;
import com.geyue.core.mapper.IntegralForMapper;
import com.geyue.core.mapper.UserMapper;
import com.geyue.core.model.IntegralFor;
import com.geyue.core.model.User;
import com.geyue.core.service.IntegralForService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Lyon on 2017/3/27.
 */
@Service
public class IntegralForServiceImpl extends BaseServiceImpl<IntegralFor> implements IntegralForService {

    @Autowired
    private IntegralForMapper integralForMapper;
    @Autowired
    private UserMapper userMapper;

    public PageInfo<IntegralFor> getPageList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<IntegralFor> list = integralForMapper.isOkList();
        PageInfo<IntegralFor> page = new PageInfo<IntegralFor>(list);
        return page;
    }

    public Res ok(Integer id) {

        IntegralFor integralFor = integralForMapper.selectByPrimaryKey(id);

        User self = userMapper.getByMobile(integralFor.getMobile());

        if(self.getIntegral() < integralFor.getIntegral())
            return Res.fail("用户积分不足!");

        User for_ = userMapper.getByMobile(integralFor.getForMobile());

        if(for_ == null)
            return Res.fail("被转让用户不存在!");

        integralFor.setIsOk(IntegralFor.ok);
        if(integralForMapper.updateByPrimaryKeySelective(integralFor) > 0){
            if(userMapper.subtraction(integralFor.getMobile(),integralFor.getIntegral()) > 0){
                if(userMapper.addition(integralFor.getForMobile(),integralFor.getIntegral()) > 0){
                    return Res.success("审核成功!");
                }
            }
        }

        return Res.fail("审核失败");
    }
}
